package com.atguigu.juc.date928;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: shenhao
 * @CreatTime: 2024/9/28 18:24
 * @Version: 1.0
 * 字母和数字循环输出 1A2B3C
 */
public class NumAndWord {
    public static void main(String[] args) {
        NumAndWordLine andWordLine = new NumAndWordLine();
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                try {
                    andWordLine.printNum();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "数字输出");
        thread1.start();
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                try {
                    andWordLine.printWord();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "字母输出");
        thread2.start();
    }
}
//高内聚,低耦合,方法要写到资源类中,并且等待,唤醒,标志位都要写在资源类中
class NumAndWordLine {
    private int num = 0;
    private Character word = 'A';
    int flag = 0;
    public synchronized void printNum() throws InterruptedException {
        while (flag != 0) {
            this.wait();
        }
        System.out.print(++num);
        flag = 1;
        this.notifyAll();
    }

    public synchronized void printWord() throws InterruptedException {
        while (flag != 1) {
            this.wait();
        }
        System.out.print(word++);
        flag = 0;
        this.notifyAll();
    }
}
